package framework.system;

import java.nio.ByteBuffer;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.security.MessageDigest;


public class FrontEndImpl extends UnicastRemoteObject implements FrontEnd {

	private final BackEndImpl backEnd;
	private static MessageDigest m;



	public FrontEndImpl(BackEndImpl backEnd) throws Exception {
		super();
		this.backEnd = backEnd;
		m = MessageDigest.getInstance("SHA-1");
	}

	private static String generateKey(String initialKey) throws Exception {
		byte[] initialBytes = initialKey.getBytes("ASCII");
		
		byte[] digestBytes = m.digest(initialBytes);
		ByteBuffer digestBuffer = ByteBuffer.allocate(digestBytes.length);
		digestBuffer.put(digestBytes);
		digestBuffer.rewind();
		
		long finalKeyL = digestBuffer.getLong();
		String finalRequest = Long.toBinaryString(finalKeyL).substring(1);

		return finalRequest;
	}
	
	@Override
	public String[] get(String key) throws Exception {
		String requestKey = generateKey(key);
		return backEnd.get(requestKey);
	}

	@Override
	public void put(String key, String value) throws Exception {
		String requestKey = generateKey(key);
		backEnd.put(requestKey, value);
	}

	@Override
	public String[] remove(String key) throws Exception {
		String requestKey = generateKey(key);
		return backEnd.remove(requestKey);
	}

}
